package com.example.netty.nio.serverAndClient;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Server {
    public static void main(String[] args) throws IOException {
        //1.创建服务器
        ServerSocketChannel channel = ServerSocketChannel.open();
        //改为非阻塞模式
        //channel.configureBlocking(false);
        //2.绑定端口
        channel.bind(new InetSocketAddress(8080));
        //3.创建连接集合
        List<SocketChannel> list = new ArrayList<>();
        //4.创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        while (true){
            //5.监听客户端与accept与客户端建立连接
            System.out.println("监听客户端");
            SocketChannel socketChannel = channel.accept();
            System.out.println("监听到客户端,创建连接: " + socketChannel);
            list.add(socketChannel);
                System.out.println("准备读取客户端发送内容");
                int len = socketChannel.read(byteBuffer);
                if (len == -1){
                    System.out.println("客户端断开连接");
                    break;
                }
                System.out.println("读取客户端内容完毕");
                byteBuffer.flip();
                System.out.println(StandardCharsets.UTF_8.decode(byteBuffer) + socketChannel.toString());
                byteBuffer.clear();
                byteBuffer.clear();

        }
    }
}
